/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.form;

import cz.muni.fi.pb138.jprvyd.*;
import cz.muni.fi.pb138.jprvyd.gui.list.PaymentsList;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Jan
 */
public class PaymentForm extends javax.swing.JFrame {

    int rowIndex;
    public Payment payment = null;
    private SwingWorker swingWorker;
    PaymentManager paymentManager;
    PaymentsList frame;
    private final boolean ADD = true;
    private final boolean EDIT = false;
    private boolean action;

    /**
     * Creates new form InvoiceGui
     */
    public PaymentForm() {
        this.payment = new Payment();
        this.rowIndex = -1;
        this.paymentManager = new PaymentManagerImpl();
        action = ADD;
        initComponents();
    }

    public PaymentForm(PaymentsList frame) {
        this.frame = frame;
        this.payment = new Payment();
        this.rowIndex = -1;
        this.paymentManager = new PaymentManagerImpl();
        action = ADD;
        initComponents();

        Calendar calendar = new GregorianCalendar();
        DateFormat dateFormatter = new SimpleDateFormat("dd. MM. yyyy");
        String date = dateFormatter.format(calendar.getTime());

        textFieldDate.setText(date);

    }

    public PaymentForm(PaymentsList frame, Payment payment) {
        this.frame = frame;
        this.payment = payment;
        rowIndex = -1;
        this.paymentManager = new PaymentManagerImpl();
        action = EDIT;
        initComponents();

        int variableSymbol = payment.getVariableSymbol();
        String bankAccount = payment.getBankAccount();
        int money = payment.getMoney();

        DateFormat dateFormatter = new SimpleDateFormat("dd. MM. yyyy");
        String date = dateFormatter.format(payment.getDate());

        this.textFieldBankAccount.setText(bankAccount);
        this.textFieldDate.setText(date);
        this.textFieldVarSymbol.setText(Integer.toString(variableSymbol));
        this.textFieldMoney.setText(Integer.toString(money));

    }

    private class savePaymentSwingWorker extends SwingWorker<Integer, Void> {

        Payment payment;
        private final boolean ADD = true;
        private final boolean EDIT = false;
        private boolean action;
        PaymentManager paymentManager;

        public savePaymentSwingWorker(Payment payment, boolean action, PaymentManager paymentManager) {
            this.payment = payment;
            this.action = action;
            this.paymentManager = paymentManager;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            if (action == ADD) {
                paymentManager.createPayment(payment);
                frame.refreshPayments(payment, frame.ADD);
            } else if (action == EDIT) {
                paymentManager.updatePayment(payment);
                frame.refreshPayments(payment, frame.EDIT);
            }
            return 0;
        }

        @Override
        protected void done() {
            swingWorker = null;

        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelDate = new javax.swing.JLabel();
        labelEndDate = new javax.swing.JLabel();
        labelVarSymbol = new javax.swing.JLabel();
        textFieldMoney = new javax.swing.JTextField();
        textFieldDate = new javax.swing.JTextField();
        textFieldBankAccount = new javax.swing.JTextField();
        buttonSave = new javax.swing.JButton();
        buttonCance = new javax.swing.JButton();
        textFieldVarSymbol = new javax.swing.JTextField();
        labelDate1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("JPrVyd - Managing payments");

        labelDate.setText("Bank account:");

        labelEndDate.setText("Date:");

        labelVarSymbol.setText("Money amount:");

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCance.setText("Cancel");
        buttonCance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCanceActionPerformed(evt);
            }
        });

        labelDate1.setText("Variable symbol:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(buttonSave, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 216, Short.MAX_VALUE)
                        .addComponent(buttonCance, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelVarSymbol)
                            .addComponent(labelEndDate)
                            .addComponent(labelDate)
                            .addComponent(labelDate1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textFieldVarSymbol)
                            .addComponent(textFieldBankAccount, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textFieldDate, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textFieldMoney, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelDate1)
                    .addComponent(textFieldVarSymbol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelDate)
                    .addComponent(textFieldBankAccount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEndDate)
                    .addComponent(textFieldDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textFieldMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelVarSymbol, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCance))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCanceActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCanceActionPerformed

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
      
        DateFormat dateParser = new SimpleDateFormat("dd. MM. yyyy");
        String varSymbolString = textFieldVarSymbol.getText();
        String bankAccount = textFieldBankAccount.getText();
        String dateString = textFieldDate.getText();
        String moneyAmountString = textFieldMoney.getText();

        if (varSymbolString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter variable sybol");
        } else if (bankAccount.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter bank account");
        } else if (dateString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter date (DD. MM. YYYY)");
        } else if (moneyAmountString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter money amount");
        } else {
            buttonSave.setEnabled(false);
            boolean ok = true;
            Date date = null;
            try {
                date = dateParser.parse(textFieldDate.getText());
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(rootPane, "Enter a correct date (DD. MM. YYYY)");
                ok = false;
            }
            int varSymbol = 0;
            try {
                varSymbol = Integer.parseInt(textFieldVarSymbol.getText());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(rootPane, "Variable symbol must be a number");
                ok = false;
            }
            int money = 0;
            try {
                money = Integer.parseInt(textFieldMoney.getText());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(rootPane, "Money amount must be a number");
                ok = false;
            }            
            if (ok) {
                payment.setMoney(money);
                payment.setDate(date);
                payment.setBankAccount(bankAccount);
                payment.setVariableSymbol(varSymbol);
                while (swingWorker != null) {
                    // another action in process
                }
                
                swingWorker = new savePaymentSwingWorker(payment, action, paymentManager);
                swingWorker.execute();
                this.dispose();

            } else {
                buttonSave.setEnabled(true);
            }
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaymentForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCance;
    private javax.swing.JButton buttonSave;
    private javax.swing.JLabel labelDate;
    private javax.swing.JLabel labelDate1;
    private javax.swing.JLabel labelEndDate;
    private javax.swing.JLabel labelVarSymbol;
    private javax.swing.JTextField textFieldBankAccount;
    private javax.swing.JTextField textFieldDate;
    private javax.swing.JTextField textFieldMoney;
    private javax.swing.JTextField textFieldVarSymbol;
    // End of variables declaration//GEN-END:variables
}
